import type { LocaleSetting, LocaleType } from '/#/config';
import type { State, RootState } from '@vue/runtime-core'
import type { ActionContext } from 'vuex'


import { LOCALE_KEY } from '@/enums/cacheEnum';
import { createLocalStorage } from '@/utils/cache';
import { localeSetting } from '@/settings/localeSetting';

const ls = createLocalStorage();

const lsLocaleSetting = (ls.get(LOCALE_KEY) || localeSetting) as LocaleSetting;

interface LocaleState {
  localInfo: LocaleSetting;
}

 const useLocale = {
  namespace: true,
  state: (): LocaleState => ({
    localInfo: lsLocaleSetting,
  }),
  getters: {
    getShowPicker(state: State): boolean {
      return !!state.localInfo?.showPicker;
    },
    getLocale(state: State): LocaleType {
      return state.localInfo?.locale ?? 'zh_cn';
    },
  },
  mutations:{
    localInfo( state :State, info: Partial<LocaleSetting>){
      state.localInfo = { ...state.localInfo, ...info };
    }
  },

  actions: {
    /**
     * Set up multilingual information and cache
     * @param info multilingual info
     */
    setLocaleInfo({ state ,commit}: ActionContext<State, RootState>, info: Partial<LocaleSetting>) {
        commit("localInfo",info)
      ls.set(LOCALE_KEY, state.localInfo);
    },
    initLocale({ dispatch, state }: ActionContext<State, RootState>) {
      dispatch('setLocaleInfo', { ...localeSetting, ...state.localInfo })
    }
  }
}
export default useLocale